<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\api\controller;
use think\Db;
require_once '../extend/tencent/TLSSigAPIv2.php';
class Group extends Base
{
    private $usersig;
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }
        $api = new \Tencent\TLSSigAPIv2(config('tengx')['appid'],config('tengx')['appkey']);
        $this->usersig = $api->genUserSig( "administrator" );
    }
    /**
     * 创建群（正常情况下）
     * 参数：1、uid(要加入这个群的用户id），2、name：群名字
     * @return string
     */
    public function createGroup(){
        extract(input());
        if(strlen($name) > 30){
            return json(['status'=>0,'msg'=>'名字最多7个汉字']);
        }
		$uid = trim($uid,',');
		$num = explode(',',$uid);
        if(!$uid){
            return json(['status'=>0,'msg'=>'请选择用户']);
        }
        if(!$name){
            return json(['status'=>0,'msg'=>'群名字不能为空']);
        }
        //----------------------------------------------------------
        $meets = Db::table('up_group')->count();
        $new_gid = $meets + $user_id + rand(100000,999999);
        //----------------------------------------------------------
        $uid = ',' . $uid . ',';
        $data = array();
        $data['g_name'] = $name;
        $data['g_id'] = $new_gid;
        $data['g_user_id'] = $user_id;
        $data['g_uids'] = $uid . $user_id . ',';
        $data['g_notice'] = '';
        $data['g_thumb'] = '';
        $data['g_nums'] = count($num)+1;
        $data['g_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try {
            $groupid = $data['g_id'];
            Db::table('up_group')->insert($data);
            $users = Db::table('up_u_user')->where('user_id', 'in',trim($uid,','))
                ->field('CAST(user_id AS CHAR) Member_Account')
                ->select();
            $res = $this->create($user_id,$groupid,$name,$users,$this->usersig);
            if ($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0) {
                $status = 200;
                $msg = $groupid;
            }else{
                Db::table('up_group')->where('g_id', $groupid)->delete();
                $status = 0;
                $msg = '新增失败';
            }
            Db::commit();
            $returnData['status'] = $status;
            $returnData['msg'] = $msg;
            return json($returnData);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $returnData['status'] = 0;
            $returnData['msg'] = "新增失败！";
            return json($returnData);
        }
    }
    /**
     * 创建群（孚玛和视频聊天情况下）
     * 参数：
     * type ： 1 孚玛  2 视频聊天
     * other_id：孚玛会议id或另外的那个人的id
     * @return string
     */
    public function createGroupSpecial(){
        extract(input());
//        $type = 2;
//        $other_id = 12;
//        $user_id = 13;
        if($type == 1){
            $name = '孚玛会议' . time();

            $g_id = 'fuma' . $other_id;

            $g_uids = ',' . $user_id . ',';
        }else{
            $name = '视频聊天' . time();

            $g_id = $user_id . '0' . $other_id;
            if($user_id > $other_id) $g_id = $other_id . '0' . $user_id;

            $g_uids = ',' . $user_id . ',' . $other_id . ',';
        }
        $have = Db::table('up_group_copy')->where('g_id', $g_id)->find();
        if($have){
            return json(['status' => 200, 'msg' => $g_id,'uid' => $user_id, 'uid2' => $other_id]);
        }
        $data = array();
        $data['g_name'] = $name;
        $data['g_type'] = $type;
        $data['g_id'] = $g_id;
        $data['g_user_id'] = $user_id;
        $data['g_uids'] = $g_uids;
        $data['g_notice'] = '';
        $data['g_thumb'] = '';
        $data['g_nums'] = $type;
        $data['g_time'] = date('Y-m-d H:i:s');
        Db::startTrans();
        try {
            $groupid = $data['g_id'];
            Db::table('up_group_copy')->insert($data);
            $users = [];
            if($type == 2){
                $users = Db::table('up_u_user')->where('user_id', $other_id)
                    ->field('CAST(user_id AS CHAR) Member_Account')
                    ->select();
            }
            $res = $this->create($user_id,$groupid,$name,$users,$this->usersig);
            if ($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0) {
                $status = 200;
                $msg = $groupid;
            }else{
                Db::table('up_group_copy')->where('g_id', $groupid)->delete();
                $status = 0;
                $msg = '新增失败';
            }
            Db::commit();
            $returnData['status'] = $status;
            $returnData['msg'] = $msg;
            return json($returnData);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $returnData['status'] = 0;
            $returnData['msg'] = "新增失败！";
            return json($returnData);
        }
    }

    /**
     * 如果是编辑，返回已经是群成员的id数组
     * type传2代表新增成员
     */
    public function haveUsersIds(){
        extract(input());
        if(isset($type) && $type == 2){
            $g = Db::table('up_group')
                ->where('g_id',$groupid)
                ->field('g_uids')
                ->find();
            $g['g_uids'] = trim($g['g_uids'],',');
            $ids = explode(',',$g['g_uids']);
        }else{ //代表创建群组，返回空即可
            $ids = [];
        }

        return  json(['status'=>200,'msg'=>$ids]);
    }

    /**
     * 加入群组：加人
     * 参数：1、uid(必须是数组：要加入的这些人的id)，2、群id
     * @return string
     */
    public function joinGroup(){
        extract(input());
        $g = Db::table('up_group')->where('g_id', $groupid)->find();
        $g['g_uids'] = trim($g['g_uids'],',');
        $uids = explode(',',$g['g_uids']);
        $uid = explode(',',trim($uid,','));
        if(!$uid){
            return json(['status'=>0,'msg'=>'请选择用户']);
        }
        if($g['g_status'] != 1){
            return json(['status'=>0,'msg'=>'此群已解散']);
        }
        $same = array_intersect($uids,$uid);
        if($same){
            return json(['status'=>0,'msg'=>'有相同成员']);
        }
        $all = array_merge($uids,$uid);
        if(count($all) >= 500){
            return json(['status'=>0,'msg'=>'成员已满']);
        }
        Db::startTrans();
        try {
            $users = Db::table('up_u_user')->where('user_id', 'in',$uid)
                ->field('CAST(user_id AS CHAR) Member_Account')
                ->select();
            $res = $this->joinin($this->usersig,$groupid,$users);
            if ($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0) {
                $num = count($uid);
                $ids = implode($uid,',');
                $newids = ',' . $g['g_uids'] . ',' . $ids . ',';
                Db::table('up_group')->where('g_id', $groupid)
                    ->inc('g_nums',$num)
                    ->update(['g_uids'=>$newids]);
                $status = 200;
                $msg = '成功';
            }else{
                $status = 0;
                $msg = '失败';
            }
            Db::commit();
            $returnData['status'] = $status;
            $returnData['msg'] = $msg;
            return json($returnData);
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $returnData['status'] = 0;
            $returnData['msg'] = "加入失败！";
            return json($returnData);
        }
    }
    /**
     * 退出群组：踢人（如果群主退出，则解散）
     * 参数：1、uid(必须是数组：退出的这个人的id或者是被踢的这些人的id)，2、groupid(群组id)
     * @return string
     */
    public function outGroup(){
        extract(input());
//        ---------------------------

        $g = Db::table('up_group')->where('g_id', $groupid)->find();
        $g['g_uids'] = trim($g['g_uids'],',');
        $uids = explode(',',$g['g_uids']);
//        ---------------------------
        $uid = explode(',',trim($uid,','));
        if(!$uid){
            return json(['status'=>0,'msg'=>'请选择用户']);
        }
        if(in_array($g['g_user_id'],$uid)){
            $res = $this->kill($this->usersig,$groupid);
            if ($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0) {
                Db::table('up_group')->where('g_id', $groupid)->update(['g_status'=>2]);
                return json(['status'=>200,'msg'=>'解散成功']);
            }else{
                return json(['status'=>0,'msg'=>'解散失败']);
            }
        }else{
            Db::startTrans();
            try {
                $users = Db::table('up_u_user')
                    ->where('user_id', 'in',$uid)
                    ->column('CAST(user_id AS CHAR) Member_Account');
                $res = $this->getout($this->usersig,$groupid,$users);
                if ($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0) {
                    $difids = array_diff($uids,$uid);
                    $ids = implode($difids,',');
                    $newids = ',' . $ids . ',';
                    Db::table('up_group')->where('g_id', $groupid)
                        ->update(['g_uids'=>$newids,'g_nums' => count($difids)]);
                    $status = 200;
                    $msg = '成功';
                }else{
                    $status = 0;
                    $msg = '失败';
                }
                Db::commit();
                $returnData['status'] = $status;
                $returnData['msg'] = $msg;
                return json($returnData);
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $returnData['status'] = 0;
                $returnData['msg'] = "失败！";
                return json($returnData);
            }
        }

    }

    /**
     * 我的群聊
     * type：1我创建的  2我加入的
     * @return string
     */
    public function myGroup(){
        extract(input());
        if(!isset($type) || !$type){
            $type = 1;
        }
        $where = [
            'g_status' => 1,
            'g_uids' => ['like',"%,$user_id,%"],
        ];
        if($type == 1){
            $where['g_user_id'] = $user_id;
        }else{
            $where['g_user_id'] = ['<>',$user_id];
        }
        $res = Db::table('up_group')
            ->where($where)
            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 我的某个群聊详情
     * （只有群主才可以减人和改名字）
     * @return string
     */
    public function myGroupInfo(){
        extract(input());
        $res = Db::table('up_group')
            ->where('g_id', $groupid)
            ->find();
        $uids = trim($res['g_uids'],',');
        $users = Db::table('up_u_user u')
            ->join('up_company c','u.user_hospital = c.c_id','left')
            ->join('up_company_team ct','u.user_room = ct.ct_id','left')
            ->where('user_id','in',$uids)
            ->field('user_id,user_type,user_username,user_image,user_hospital,user_room,c_name,ct_name')
            ->select();
        return json(['status'=>200,'msg'=>$res,'users'=>$users]);
    }
    /**
     * 修改我的群聊
     * （只有群主才可以减人和更改公告）
     * @return string
     */
    public function updateGroup(){
        extract(input());
        if(strlen($name) > 30){
            return json(['status'=>0,'msg'=>'名字最多7个汉字']);
        }
        $data = array();
        $data['g_name'] = $name;
        $g_name = Db::table('up_group')->where('g_id', $groupid)->value('g_name');
        if(trim($name,' ') == trim($g_name,' ')){
            return json(['status'=>0,'msg'=>'名字一样，请检查']);
        }
        $res = $this->editgroup($this->usersig,$groupid,$name);
        if ($res['ActionStatus'] == 'OK' && $res['ErrorCode'] == 0) {
            Db::table('up_group')->where('g_id', $groupid)
                ->update($data);
            return json(['status'=>200,'msg'=>'成功']);
        }else{
            return json(['status'=>0,'msg'=>'修改失败']);
        }
    }
    //-----------------下面暂时用不到，for tang-----------
    /**
     * 根据群的id获取这些群的信息
     *
     * @return string
     */
    public function byIdsGetGroupInfo(){
        $gids = trim($_POST['gids'],',');
        $res = Db::table('up_group')
            ->where('g_id', 'in',$gids)
//            ->where('g_status', 1)
            ->select();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * 我还在不在这个群了
     *
     * @return string
     */
    public function whereami(){
        extract(input());
        $status = Db::table('up_group')
            ->where('g_id', $groupid)
            ->where('g_uids', 'like',"%,$user_id,%")
            ->find();
        $res = Db::table('up_group')
            ->where('g_id', $groupid)
            ->find();
        if($status){
            $res['status'] = 1;//我还在
        }else{
            $res['status'] = 0;//我不在了
        }
        if($res['g_status'] == 2){ //解散比较特殊
            $res['status'] = 0;
        }
        $uids = trim($res['g_uids'],',');
        $users = Db::table('up_u_user u')
            ->join('up_company c','u.user_hospital = c.c_id','left')
            ->join('up_company_team ct','u.user_room = ct.ct_id','left')
            ->where('user_id','in',$uids)
            ->field('user_id,user_type,user_username,user_image,user_hospital,user_room,c_name,ct_name')
            ->select();
        $res['users'] = $users;
        return json(['status'=>200,'msg'=>$res]);

    }

}